<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        var rexName = /^[a-zA-Z]{2,20}$/;
        var rexPwd = /^\d{6}$/;
        var rexEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        var rexPhone = /^1[358]\d{9}$/;
        var rexBirthday = /^\d{4}-\d{2}-\d{2}/;

        var nameStr = "用户名必须是2-20个字母";
        var pwdStr = "密码必须是6位数字";
        var emailStr = "电子邮件必须是XX@XX.com格式";
        var phoneStr = "电话号码必须是13、15、18开始的11位数字";
        var birthdayStr = "生日为XXXX-XX-XX";

        var flag = false;

        function $(id) {
            return document.getElementById(id);
        }

        // var arr = document.getElementsByTagName("input");
        // for (var i = 0; i < arr.length; i++) {
        //     arr[i].onchange = function () {
        //         check(this.id);
        //     }
        // }

        // 显示信息
        function print(elemId, message, cor) {
            $(elemId).innerHTML = message;
            $(elemId).style.color = cor;
        }

        //验证表单数据
        function check(inputId, rex, str) {
            var e = $(inputId).value;
            if (e == "" || e == null) {
                print(inputId + "Span", e + "不能为空", "red");
                flag = false;
            } else {
                if (rex.test(e)) {
                    print(inputId + "Span", "验证通过", "green");
                    flag = true;
                } else {
                    print(inputId + "Span", str, "red");
                    flag = false;
                }
            }
        }

        //提交表单
        function submitForm() {
            // console.log(check(inputId, rex, str));//inputId为null
            // if(check(inputId, rex, str)){
            //     //提交表单
            //     $("register").submit();
            // }
            if (flag) {
                //提交表单
                $("register").submit();
            }
        }

    </script>
</head>
<body>
<form action="add" id="register">
    用户名：<input type="text" name="userName" id="userName" onblur="check('userName',rexName,nameStr)"/>
    <span id="userNameSpan"></span><br>
    密码：<input type="text" name="password" id="password" onblur="check('password',rexPwd,pwdStr)"/>
    <span id="passwordSpan"></span><br>
    电子邮件：<input type="text" name="email" id="email" onblur="check('email',rexEmail,emailStr)"/>
    <span id="emailSpan"></span><br>
    电话号码：<input type="text" name="phone" id="phone" onblur="check('phone',rexPhone,phoneStr)"/>
    <span id="phoneSpan"></span><br>
    生日：<input type="text" name="birthday" id="birthday" onblur="check('birthday',rexBirthday,birthdayStr)"/>
    <span id="birthdaySpan"></span><br>
    <input type="button" value="提交" onclick="submitForm()"/>
</form>

</body>
</html>